#! /usr/bin/env python3
import threading
import os
import datetime
from time import sleep

import fire


current_num = 0

def runShell(shell):
    global current_num
    current_num += 1
    print('\nStart:', shell)
    os.system(shell)
    current_num -= 1
    print('\nLeave:', shell)


def main(time, threads=2, shells='./shells.txt', monitor='./tag.txt'):
    today = datetime.datetime.today()
    dst_hour, dst_minute = [int(num) for num in time.split(':')]
    timer = datetime.datetime(today.year, today.month, today.day, dst_hour, dst_minute, 0)
    if timer <= datetime.datetime.today():
        timer = timer + datetime.timedelta(days=1)

    max_thread_num = threads
    shells_path = shells

    shell_list = []
    with open(shells_path, encoding='utf-8') as f:
        shell_list = [line for line in f.readlines() if len(line) > 1]

    i = 0
    if os.path.isfile(monitor):
        with open(monitor, 'r') as f:
            i = min(int(f.read()), len(shell_list) - 1)

    while datetime.datetime.today() < timer:
        if current_num < max_thread_num:
            shell = shell_list[i]
            threading.Thread(target=runShell, args=(shell,)).start()
            i = (i + 1) % len(shell_list)
        else:
            sleep(1)

    with open(monitor, 'w') as f:
        f.write(str(i))

    print('End...')

if __name__ == '__main__':
    fire.Fire(main)
